package com.tech.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {
	private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);
	private static final Gson GSON = new GsonBuilder()
			.setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping()
			.create();

	private static final ObjectMapper mapper = new ObjectMapper();

	static {
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	public static String objToString(Object o) {
		try {
			return mapper.writeValueAsString(o);
		} catch (Exception e) {
			LOG.error("Error Json:{}", o);
			throw new IllegalStateException(e);
		}
	}

	public static <T> T strToObject(String json, Class<T> targetClazz) {
		try {
			return mapper.readValue(json, targetClazz);
		} catch (Exception e) {
			LOG.error("Error Json:{}", json);
			throw new IllegalStateException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public static Map<String, String> strToMap(String str) {
		Map<String, String> map = new HashMap<String, String>();
		map.putAll((HashMap<String, String>) GSON.fromJson(str,
				new TypeToken<HashMap<String, String>>() {
				}.getType()));
		return map;
	}

	public static String beanToString(Object o) {
		if (o == null)
			return "";
		return GSON.toJson(o);
	}
}
